package com.lyc.controller;

import com.lyc.constant.Constant;
import com.lyc.entity.Order;
import com.lyc.entity.Product;
import com.lyc.entity.User;
import com.lyc.entity.biz.OrderBiz;
import com.lyc.entity.qo.OrderQo;
import com.lyc.entity.vo.*;
import com.lyc.service.IAddressService;
import com.lyc.service.IOrderService;
import com.lyc.utils.AccessUtil;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IOrderService orderService;

    //购物车结算商品
    @RequestMapping("/orderConfirm")
    public String makeOrder(HttpSession session, Model model) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user != null) {
            List<AddressVo> addressVoList = addressService.getMyAddress(user.getUid());
            model.addAttribute("addressList", addressVoList);
        }
        return "/order/order_confirm";
    }

    @RequestMapping("/makeOrder")
    public String makeOrder(HttpServletRequest request,HttpSession session, OrderBiz orderBiz, Model model) {
        String retUrl = request.getHeader("Referer");
        if (StringUtils.isEmpty(retUrl))
            retUrl = "/user/index";
        if (orderBiz.getTotal()<=0||orderBiz.getTotalFreight()<=0||StringUtils.isEmpty(orderBiz.getAddress())){
            model.addAttribute("content", "参数错误，无法完成交易");
            model.addAttribute("url", retUrl);
            return "/common/errorModal";
        }
        for (ProductVo productVo:orderBiz.getProductVoList()){
            if (productVo.getCount()<=0||StringUtils.isEmpty(productVo.getSize())||StringUtils.isEmpty(productVo.getColor())){
                model.addAttribute("content", "参数错误，无法完成交易");
                model.addAttribute("url", retUrl);
                return "/common/errorModal";
            }
        }
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        Order order = orderService.makeOrder(user != null ? user.getUid() : null, orderBiz);
        model.addAttribute("oid", order.getOid());
        return "/order/pay_way";
    }

    @RequestMapping("/pay")
    public String pay(HttpServletRequest request,Model model, String oid) {
        String msg = "银行付款页面";
        String retUrl = request.getHeader("Referer");
        if (StringUtils.isEmpty(retUrl))
            retUrl = "/user/index";
        if (oid == null) {
            msg = "参数缺失";
            model.addAttribute("content", msg);
            model.addAttribute("url", retUrl);
            return "/common/errorModal";
        }
        model.addAttribute("msg", msg);
        return "/common/msg";
    }

    @RequestMapping("/payForOrder")
    public String payForOrder(HttpServletRequest request,Model model, String oid) {
        String retUrl = request.getHeader("Referer");
        if (StringUtils.isEmpty(retUrl))
            retUrl = "/user/index";
        if (oid == null) {
            model.addAttribute("content", "参数缺失");
            model.addAttribute("url", retUrl);
            return "/common/errorModal";
        }
        //TODO 库存-- 销量++
        orderService.updateOrderStatusByOid(oid, Constant.WAIT4SEND_STATUS);//下单成功，等待发货
        return "redirect:/order/getMyOrders";
    }

    @RequestMapping("/getMyOrders")
    public String getMyOrders(HttpSession session, Integer status, Integer currentPage, Model model) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (currentPage == null || currentPage <= 0) {
            currentPage = 1;
        }
        PageBean<OrderVo> page = orderService.getMyOrdersByStatus(user != null ? user.getUid() : null, status, currentPage);
        model.addAttribute("page", page);
        return "/order/my_order";
    }

    @RequestMapping("/toPay")
    public String toPay(HttpServletRequest request,Model model, String oid) {
        String retUrl = request.getHeader("Referer");
        if (StringUtils.isEmpty(retUrl))
            retUrl = "/user/index";
        if (oid == null) {
            model.addAttribute("content", "参数缺失");
            model.addAttribute("url", retUrl);
            return "/common/errorModal";
        }
        return "/order/pay_way";
    }

    @RequestMapping("/handleOrderStatus")
    @ResponseBody
    public Map<String, Object> handleOrderStatus(String oid, Integer status) {
        //TODO 根据订单状态考虑不同问题，例如，下单成功：库存--销量++，取消订单：销量--库存++，退货成功：库存++销量-- ，退款成功：销量--
        Map<String, Object> result = new HashMap<>();
        result.put("status", status);
        Order order = orderService.getOrderByOid(oid);
        boolean isAccess = AccessUtil.isAccess(order.getStatus(), status);
        result.put("type", isAccess ? Constant.OPERATE_SUCCESS : Constant.OPERATE_FAIL);
        if (isAccess)
            orderService.updateOrderStatusByOid(oid, status);
        return result;
    }

    @RequestMapping("/getOrderDetailByOid")
    public String getOrderDetailByOid(String oid, Model model) {
        OrderVo orderVo = orderService.getOrderDetailByOid(oid);
        model.addAttribute("orderVo", orderVo);
        return "/order/order_detail";
    }

    @RequestMapping("/deleteOrder")
    public String deleteOrder(String oid) {
        orderService.deleteOrderByOid(oid);
        return "redirect:/order/getMyOrders";
    }

    @RequestMapping("/orderList")
    public String orderList(OrderQo qo, Model model) {
        Integer currentPage = qo.getCurrentPage();
        if (currentPage == null || currentPage <= 0)
            currentPage = 1;
        PageBean<OrderUsernameVo> page = orderService.getOrderByConditions(qo, currentPage, Constant.ORDER_PAGE_SIZE);
        model.addAttribute("page", page);
        model.addAttribute("orderQo", qo);
        return "/admin/order_list";
    }

    @RequestMapping("/sendGoods")
    @ResponseBody
    public Map<String, Object> sendGoods(Order order) {
        Map<String, Object> result = new HashMap<>();
        if (order != null) {
            Order o = null;
            if (!StringUtils.isEmpty(order.getOid())) {
                o = orderService.getOrderByOid(order.getOid());
            }
            if (order.getStatus() != null) {
                o.setStatus(order.getStatus());
            }
            if (!StringUtils.isEmpty(order.getPostCompany())) {
                o.setPostCompany(order.getPostCompany());
            }
            if (!StringUtils.isEmpty(order.getPostCode())) {
                o.setPostCode(order.getPostCode());
            }
            orderService.updateOrder(o);
            result.put("type", Constant.OPERATE_SUCCESS);
            result.put("status", order.getStatus());
        } else {
            result.put("type", Constant.OPERATE_FAIL);
        }
        return result;
    }

    @RequestMapping("/delOrder")
    public String delOrder(String oid){
        if (!StringUtils.isEmpty(oid)){
            orderService.deleteOrderByOid(oid);
        }
        return "redirect:/order/orderList";
    }

    @RequestMapping("/getOrderDetail")
    public String getOrderDetail(String oid,Model model){
        OrderVo orderVo = orderService.getOrderDetailByOid(oid);
        model.addAttribute("orderVo", orderVo);
        return "/admin/order_detail";
    }

    @RequestMapping("/delOrderByIds")
    public String delOrderByIds(OrderQo orderQo){
        if (orderQo!=null&&orderQo.getOids()!=null&&orderQo.getOids().size()>0){
            orderService.deleteBatchByOids(orderQo.getOids());
        }
        return "redirect:/order/orderList";
    }
}
